#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>

#define BUFSIZE 128

int main(int argc, char **argv)
{
	int pfd[2] = {};
	int music_fd;
	pid_t pid;

	int ret;
	char buf[BUFSIZE] = {};

	music_fd = open(argv[1], O_RDONLY);
	if (-1 == music_fd) {
		perror("Error opening music file");
		exit(1);
	}

	if (-1 == pipe(pfd)) {
		close(music_fd);

		perror("Error creating pipe");
		exit(1);
	}
	pid = fork();
	if (0 == pid) {
		close(pfd[1]); // 关闭子进程写
		
		dup2(pfd[0], 0); // 将子进程读重定向到标准输入
		execlp("mplayer", "mplayer", "-", NULL);

		perror("Error executing mplayer");
		exit(1);
	}
	
	close(pfd[0]); // 关闭父进程读

	while (1) {
		ret = read(music_fd, buf, BUFSIZE);
		if (-1 == ret) {
			perror("Error reading from music file");
			exit(1);
		}
		if (0 == ret) {
			break;
		}
		write(pfd[1], buf, ret);
	}

	close(music_fd);
	close(pfd[1]); // 关闭父进程写

	wait(NULL);

	return 0;
}
